package com.cloudspace.jindun.activity.locate;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.cloudspace.jindun.JindunApp;
import com.cloudspace.jindun.R;
import com.cloudspace.jindun.activity.CustomTitleBaseActivity;
import com.cloudspace.jindun.activity.locate.model.MyItem;
import com.cloudspace.jindun.log.APPLog;
import com.cloudspace.jindun.model.LocateArea;
import com.cloudspace.jindun.model.LocateAreaResult;
import com.cloudspace.jindun.model.LocatePerson;
import com.cloudspace.jindun.module.ActionItem;
import com.cloudspace.jindun.utils.MMAlert;
import com.cloudspace.jindun.utils.ObjUtil;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.maps.android.clustering.ClusterManager;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zengxianhua on 17/3/3.
 */

public class LocateSuperviseActivity extends CustomTitleBaseActivity implements OnMapReadyCallback {
    private MapView mMap;
    private LocateAreaResult areaResult;

    private static final String TAG = LocateSuperviseActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_locate_supervise, true);
        getTitleBar().setSimpleMode(getResources().getString(R.string.supervise_title), new ActionItem(
                getResources().getString(R.string.supservise_statistics),
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        LocateStatisticsActivity.showActivity(LocateSuperviseActivity.this, areaResult);
                    }
                }

        ));

        mMap = (MapView) findViewById(R.id.mapview);
        mMap.onCreate(savedInstanceState);

        try {
            MapsInitializer.initialize(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
        int errorCode = GooglePlayServicesUtil
                .isGooglePlayServicesAvailable(this);

        if (ConnectionResult.SUCCESS == errorCode) {
            mMap.getMapAsync(this);
        } else {
            MMAlert.showAlert(this,
                    JindunApp.getInstance().getResources().getString(R.string.permission_locate)
            );
        }

        if (getIntent() != null && getIntent().getSerializableExtra("areas") != null) {
            areaResult = (LocateAreaResult) getIntent().getSerializableExtra("areas");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mMap != null) {
            mMap.onResume();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mMap != null) {
            mMap.onPause();
        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        demo(googleMap);
//        personLocateMarkup(googleMap);
    }

    private void demo(GoogleMap googleMap) {
        googleMap.setMyLocationEnabled(true);
        mClusterManager = new ClusterManager<MyItem>(this, googleMap);
        googleMap.setOnCameraIdleListener(mClusterManager);

        try {
            readItems(googleMap);
        } catch (JSONException e) {
            Toast.makeText(this, "Problem reading list of markers.", Toast.LENGTH_LONG).show();
        }
    }

    private void readItems(GoogleMap googleMap) throws JSONException {
        List<MyItem> items = new ArrayList<>();

        boolean locateFirst = true;

        if (areaResult != null && !ObjUtil.isEmpty(areaResult.data)) {
            for (LocateArea area : areaResult.data) {
                if (area != null && !ObjUtil.isEmpty(area.perList)) {
                    for (LocatePerson personStatistics : area.perList) {
                        if (personStatistics != null) {
                            MyItem item = new MyItem(personStatistics.userCoordinateW, personStatistics.userCoordinateJ);
                            items.add(item);
                        }

                        if (locateFirst) {
                            googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(personStatistics.userCoordinateW,
                                    personStatistics.userCoordinateJ), 13));
                            locateFirst = false;
                        }
                    }
                }
            }
        }

        mClusterManager.addItems(items);
    }

    private void personLocateMarkup(GoogleMap googleMap) {
//        if (HeartService.isReady()){
//            Location location = HeartService.getInstance().getLocation();
//
//            if (location != null){
//                LatLng curLocation = new LatLng(location.getLatitude(), location.getLongitude());
//
//                googleMap.setMyLocationEnabled(true);
//                googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(curLocation, 13));
//
//                APPLog.zxhLog(TAG + String.format(" add marker:%s,%s", String.valueOf(curLocation.longitude), String.valueOf(curLocation.latitude)));
//                googleMap.addMarker(new MarkerOptions()
//                        .title("me")
//                        .position(curLocation));
//            }
//
//        }

        if (areaResult != null && !ObjUtil.isEmpty(areaResult.data)) {
            for (LocateArea area : areaResult.data) {
                if (area != null && !ObjUtil.isEmpty(area.perList)) {
                    for (LocatePerson personStatistics : area.perList) {
                        if (personStatistics != null) {
                            LatLng curLocation = new LatLng(personStatistics.userCoordinateW, personStatistics.userCoordinateJ);
                            APPLog.zxhLog(TAG + String.format(" add marker:%s,%s", String.valueOf(curLocation.longitude), String.valueOf(curLocation.latitude)));

                            googleMap.setMyLocationEnabled(true);
                            googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(curLocation, 13));

                            googleMap.addMarker(new MarkerOptions()
                                    .title(personStatistics.userName)
                                    .position(curLocation));
                        }

                    }
                }
            }
        }
    }

    private ClusterManager<MyItem> mClusterManager;

    public static void showActivity(Context context, LocateAreaResult result) {
        Intent intent = new Intent(context, LocateSuperviseActivity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }

        intent.putExtra("areas", result);

        context.startActivity(intent);
    }
}
